package net.guerlab.smart.platform.user.web.controller.user;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import net.guerlab.smart.platform.basic.auth.annotation.IgnoreLogin;
import net.guerlab.smart.platform.commons.exception.UnsupportedLoginModeException;
import net.guerlab.smart.platform.user.web.controller.AbstractOauthControlPanelController;
import net.guerlab.smart.platform.user.web.domain.LoginResponse;
import net.guerlab.smart.wx.cp.spring.exception.IsNotCompanyUserException;
import net.guerlab.smart.wx.cp.spring.exception.WxCpCodeEmptyException;
import net.guerlab.smart.wx.cp.spring.manager.WxCpServiceManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 企业微信-控制面板
 *
 * @author guer
 */
@Api(tags = "企业微信-控制面板")
@RestController("/user/wx/cp/controlPanel")
@RequestMapping("/user/wx/cp/controlPanel")
public class WxCpControlPanelController extends AbstractOauthControlPanelController {

    private WxCpServiceManager wxCpServiceManager;

    @Override
    protected String getOauthType() {
        return "WORK_WEIXIN";
    }

    @IgnoreLogin
    @ApiOperation("通过code登录")
    @GetMapping("/{agentId}/loginByCode")
    public LoginResponse loginByCode(@ApiParam(value = "agentId", required = true) @PathVariable Integer agentId,
            @ApiParam(value = "code", required = true) @RequestParam String code, HttpServletRequest request)
            throws Exception {
        if (StringUtils.isBlank(code)) {
            throw new WxCpCodeEmptyException();
        }

        WxCpOauth2UserInfo userInfo = getWxCpService(agentId).getOauth2Service().getUserInfo(code);

        String userId = userInfo.getUserId();

        if (StringUtils.isBlank(userId)) {
            throw new IsNotCompanyUserException();
        }

        return getLoginSucceedDTO(findUser(userId), userId, request, getOauthType());
    }

    private WxCpService getWxCpService(Integer agentId) {
        if (wxCpServiceManager == null) {
            throw new UnsupportedLoginModeException();
        }
        WxCpService wxCpService = wxCpServiceManager.getWxCpService(agentId);
        if (wxCpService == null) {
            throw new UnsupportedLoginModeException();
        }
        return wxCpService;
    }

    @Autowired(required = false)
    public void setWxCpServiceManager(WxCpServiceManager wxCpServiceManager) {
        this.wxCpServiceManager = wxCpServiceManager;
    }
}
